﻿using Microsoft.EntityFrameworkCore;
using Tpl.Domain;

namespace Tpl.Ef.Pe
{
    public class LibraryDbContext:DbContext
    {
        private readonly EFEntityInfo _efEntitysInfo;

        public LibraryDbContext(DbContextOptions options, EFEntityInfo efEntityInfo) : base(options)
        {
            _efEntitysInfo = efEntityInfo;

            ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var (Assembly, Types) = _efEntitysInfo.EFEntitiesInfo;

            // 加载所有的Entity
            foreach (var entityType in Types)
            {
                modelBuilder.Entity(entityType);
            }

            // 加载全局的默认配置
            modelBuilder.AdjustPeDefaultAction();

            // 加载所有的Config
            modelBuilder.ApplyConfigurationsFromAssembly(Assembly);

            base.OnModelCreating(modelBuilder);
        }
    }
}
